package com.github.bridge.client.esign;

import com.dtflys.forest.backend.ContentType;
import com.dtflys.forest.callback.SuccessWhen;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.github.bridge.util.JacksonUtil;
import org.springframework.http.HttpStatus;

public class ESignSuccessCondition implements SuccessWhen {

    @Override
    public boolean successWhen(ForestRequest forestRequest, ForestResponse forestResponse) {
        // {"timestamp":"2024-08-23T12:42:04.815+0800","status":404,"error":"Not Found","message":"No message available","path":"/V1/files/getDownloadUrl"}
        String content = forestResponse.getContent();
        // 这里可以判断业务code
        boolean ok = forestResponse.statusIs(HttpStatus.OK.value());
        ContentType contentType = forestResponse.getContentType();
        if (ok && (ContentType.APPLICATION_JSON.equalsIgnoreCase(contentType.getType())
                || "application".equals(contentType.getType()))) {
            ESignResult bean = JacksonUtil.toBean(content, ESignResult.class);
            if (!bean.success()) {
                ok = false;
            }
        }
        boolean noException = forestResponse.noException();
        return  noException && ok;
    }
}
